package com.it.cloud.itagent;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *  处理器
 *
 * @author 司马缸砸缸了
 * @date 2019/8/2 11:08
 * @description
 */
public class JobHandler implements HttpHandler {
    /**
     * 处理线程池
     */
    private ExecutorService fixedThreadPool = Executors.newFixedThreadPool(100);
    /**
     * 响应格式
     */
    private final static String APPLICATION_JSON = "application/json;charset=UTF-8";
    private final static String TEXT_PLAIN = "text/plain;charset=UTF-8";

    @Override
    public void handle(HttpExchange exchange) throws IOException {

        // 该命令可能在新的线程、已入池的线程或者正调用的线程中执行，这由 Executor 实现决定。
        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                //获得查询字符串(get)
                String queryString = exchange.getRequestURI().getQuery();
                Map<String, String> queryStringInfo = formData2Dic(queryString);
                //获得表单提交数据(post)
                String postString = null;
                try {
                    postString = IOUtils.toString(exchange.getRequestBody());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Map<String, String> postInfo = formData2Dic(postString);

                //返回
                String response = "hello httpserver";
                // 响应
                writeResponse(exchange, response, APPLICATION_JSON);
            }
        });
    }

    /**
     * 响应
     *
     * @param httpExchange
     * @param response
     * @param contentType
     */
    private static void writeResponse(HttpExchange httpExchange, String response, String contentType) {
        if (contentType != null) {
            httpExchange.getResponseHeaders().set("Content-Type", contentType);
        }
        try {
            //设置响应头
            httpExchange.sendResponseHeaders(200, response.length());
        } catch (IOException e) {
            e.printStackTrace();
        }

        OutputStream os = httpExchange.getResponseBody();
        try {
            os.write(response.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 解析参数
     *
     * @param formData
     * @return
     */
    public static Map<String, String> formData2Dic(String formData) {
        Map<String, String> result = new HashMap<>();
        if (formData == null || formData.trim().length() == 0) {
            return result;
        }
        final String[] items = formData.split("&");
        Arrays.stream(items).forEach(item -> {
            final String[] keyAndVal = item.split("=");
            if (keyAndVal.length == 2) {
                try {
                    final String key = URLDecoder.decode(keyAndVal[0], "utf8");
                    final String val = URLDecoder.decode(keyAndVal[1], "utf8");
                    result.put(key, val);
                } catch (UnsupportedEncodingException e) {
                }
            }
        });
        return result;
    }

}
